package cn.rumoss.jvm.deep.gc;

/**
 * -verbose:class 打印详细类加载信息
 * @author xiaotang
 *
 */
public class FinalizeEscapeGC {

	public static FinalizeEscapeGC SAVE_HOOK = null;
	
	public void isAlive() {
		System.out.println("我还活着，哈哈~");
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		System.out.println("finalize方法被执行...");
		FinalizeEscapeGC.SAVE_HOOK = this;// 重新建立关联
	}
	
	public static void main(String[] args) throws Exception {

		SAVE_HOOK = new FinalizeEscapeGC();
		
		// 第一次
		SAVE_HOOK = null;
		System.gc();
		
		// 考虑到 finalize 方法优先级低，暂停0.5秒等待它
		Thread.sleep(500);
		
		if(SAVE_HOOK!=null) {
			SAVE_HOOK.isAlive();
		}else {
			System.out.println("对象被回收了哦~");
		}
		
		// 第二次
		SAVE_HOOK = null;
		System.gc();
		Thread.sleep(500);
		if(SAVE_HOOK!=null) {
			SAVE_HOOK.isAlive();
		}else {
			System.out.println("对象被回收了哦~");
		}
		
	}

}
